//Runs both clientside and serverside

local GM = GM or gmod.GetGamemode()

GM.items = {}
GM.itembases = {}

function GM:ParseItems()
	Msg("Parsing base item\n");
	local ITEMFOLDER = "wintersurvival/gamemode/items/"
	
	local iterator = file.Find(ITEMFOLDER.."*.lua", LUA_PATH)
	local found = false
	for i = 1,#iterator do
		if iterator[i] == "base.lua" then
			table.insert(iterator,1,table.remove(iterator,i))
			found = true
			break
		end
	end
	
	if not found then
		error(ITEMFOLDER .. "base.lua is missing!\n")
		return
	end
	
	Msg("Parsing items\n");
	for k,v in pairs(iterator) do
		self:ParseItem(v)
	end
	Msg("Finished parsing items\n");
end

function GM:ParseItem(v)
	local ITEMFOLDER = "wintersurvival/gamemode/items/"
	
	ITEM = self:NewItem()
	
	AddCSLuaFile(ITEMFOLDER..v)
	include(ITEMFOLDER..v)
	
	local ITEM = _G.ITEM
	_G.ITEM = nil
	
	//Precache
	if ITEM.onPrecache then
		local b,err = pcall(ITEM.onPrecache,ITEM)
		if not b then
			Error("\n",err)
		end
	end
	
	//TODO: Add class inheritance for bases
	if ITEM.base then
		wsUID = wsUID + 1
		
		ITEM.BaseClass = {
			wsUID = wsUID,
		}
		
		//Recursive parse
		self:ParseItem(tostring(ITEM.base) .. ".lua")
		
		for k,v in pairs(self.items[ITEM.base]) do
			if k ~= "wsUID" and k ~= "base" and k~= "isbase" then
				if not ITEM[k] then
					ITEM[k] = v
				else
					ITEM.BaseClass[k] = v
				end
			end
		end
		
		self.items[ITEM.class] = ITEM
	elseif ITEM.class ~= "base" then
		wsUID = wsUID + 1
		
		ITEM.BaseClass = {
			wsUID = wsUID,
		}
		
		for k,v in pairs(self.items.base) do
			if k ~= "wsUID" and k ~= "base" and k~= "isbase" then
				if not ITEM[k] then
					ITEM[k] = v
				else
					ITEM.BaseClass[k] = v
				end
			end
		end
		
		self.items[ITEM.class] = ITEM
	else
		self.items.base = ITEM
	end
	
	
	//PrintTable(ITEM)
end

wsUID = wsUID or 0
function GM:NewItem()
	wsUID = wsUID + 1
	
	local out = {
		wsUID = wsUID,
	}
	
	return out
end
